package com.shujia.flink.core

import org.apache.flink.contrib.streaming.state.EmbeddedRocksDBStateBackend
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend
import org.apache.flink.streaming.api.CheckpointingMode
import org.apache.flink.streaming.api.environment.CheckpointConfig.ExternalizedCheckpointCleanup
import org.apache.flink.streaming.api.scala._

object Demo15RocksDB {
  def main(args: Array[String]): Unit = {
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    /**
     * 打开flink的checkpoint
     *
     */
    /*

        // 每 1000ms 开始一次 checkpoint
        env.enableCheckpointing(1000)
        // 高级选项：
        // 设置模式为精确一次 (这是默认值)
        env.getCheckpointConfig.setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE)

        // 确认 checkpoints 之间的时间会进行 500 ms
        env.getCheckpointConfig.setMinPauseBetweenCheckpoints(500)

        // Checkpoint 必须在一分钟内完成，否则就会被抛弃
        env.getCheckpointConfig.setCheckpointTimeout(60000)

        // 允许两个连续的 checkpoint 错误
        env.getCheckpointConfig.setTolerableCheckpointFailureNumber(2)

        // 同一时间只允许一个 checkpoint 进行
        env.getCheckpointConfig.setMaxConcurrentCheckpoints(1)

        // 使用 externalized checkpoints，这样 checkpoint 在作业取消后仍就会被保留
        //RETAIN_ON_CANCELLATION: 当任务取消时保留checkpoint
        env.getCheckpointConfig.setExternalizedCheckpointCleanup(
          ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION)

        /**
         * 需要设置flink checkpoint保存状态的位置
         *
         */

        env.setStateBackend(new EmbeddedRocksDBStateBackend(true))
        //将状态保存到hdfs中
        env.getCheckpointConfig.setCheckpointStorage("hdfs://master:9000/flink/checkpoint")
    */


    val linesDS: DataStream[String] = env.socketTextStream("master", 8888)

    val wordsDS: DataStream[String] = linesDS.flatMap(_.split('<'))

    val kvDS: DataStream[(String, Int)] = wordsDS.map((_, 1))

    val keyByDS: KeyedStream[(String, Int), String] = kvDS.keyBy(_._1)

    /**
     * sum: 底层使用了flink的状态保存之前的计算结果
     * flink的状态会被checkpoint持久化到hdfs中，任务被取消或者执行失败可以恢复之前的计算结果
     */
    val countDS: DataStream[(String, Int)] = keyByDS.sum(1)

    countDS.print()

    env.execute()

  }

}
